package cat.joronya.supermanager.europeo.privateleague;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import cat.joronya.supermanager.europeo.R;
import cat.joronya.supermanager.europeo.service.CreatePrivateLeagueHandler;
import cat.joronya.supermanager.europeo.service.PrivateLeagueHandler;
import cat.joronya.supermanager.europeo.service.SupermanagerServiceHelper;

/**
 * Activitat per crear lligues privades.
 * @author pol
 */
public class CreatePrivateLeagueActivity extends Activity 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	private static final int PROGRESS_CREATE = 1;
	
	// the progress dialog
	ProgressDialog progress = null;
	
	/** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_private_league);
    
		// amaguem el ProgressBar, sempre amagat, tenim un progress dialog
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_create_loading);
        progressBar.setVisibility(View.INVISIBLE);        
	}
	
	/**
     * Metode on creem el/s dialeg de la activity.
     * Nomes en tenim un, passem del id.
     */
    @Override
    public Dialog onCreateDialog(int id)
    {
    	progress = ProgressDialog.show(this, "", 
    		getResources().getString(R.string.private_league_create_progress_creating), true);
    	progress.setCancelable(false);
    	return progress;
    }
	
	public void createPrivateLeague(View view) 
	{
		Log.d(TAG,"CreatePrivateLeagueActivity createPrivateLeague...");
		
		// check al name
		EditText nameView = (EditText)findViewById(R.id.private_league_create_name);
		final String name = nameView.getText().toString();
		if( name.equals("") )
		{
			nameView.requestFocus();
			Toast.makeText(this, R.string.private_league_create_name_error, Toast.LENGTH_LONG).show();
			return;
		}

		// check als passwords
		EditText pass1View = (EditText)findViewById(R.id.private_league_create_password1);
		final String pass1 = pass1View.getText().toString();
		EditText pass2View = (EditText)findViewById(R.id.private_league_create_password2);
		final String pass2 = pass2View.getText().toString();
		if( !pass1.equals(pass2) )
		{
			pass1View.setText("");
			pass2View.setText("");
			pass1View.requestFocus();
			Toast.makeText(this, R.string.private_league_create_pass_error, Toast.LENGTH_LONG).show();
			return;
		}
		
		// recuperem el max equips, numeric o blanc
		EditText maxEquipView = (EditText)findViewById(R.id.private_league_create_max_teams);
		final String maxEquips = maxEquipView.getText().toString();
		
		// recuperem el max equips per player, numeric o blanc
		EditText maxEquipPlayerView = (EditText)findViewById(R.id.private_league_create_max_teams_player);
		final String maxEquipsPlayer = maxEquipPlayerView.getText().toString();
		
		// recuperem els emails
		EditText emailsView = (EditText)findViewById(R.id.private_league_create_emails);
		String[] emails = emailsView.getText().toString().split("\n");
		String emailsString = "";
		for(int i=0; i<emails.length; i++)
		{
			// si buit, continuem
			if( emails[i].equals("") )
				continue;
			
			// check valid email
			if( !android.util.Patterns.EMAIL_ADDRESS.matcher(emails[i]).matches() )
			{
				emailsView.requestFocus();
				Toast.makeText(this, R.string.private_league_create_email_error, Toast.LENGTH_LONG).show();
				return;
			}
			if( !emailsString.equals("") )
				emailsString += "\r\n";
			emailsString += emails[i];
		}
		final String emailsToSend = emailsString;
		
    	// ocultem el teclat
    	InputMethodManager imm = (InputMethodManager)getSystemService(
    		      Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(emailsView.getWindowToken(), 0);
    	
		// mostrem el ProgressDialog
		showDialog(PROGRESS_CREATE);
        
		// cridar service per crear private league
		
		new Thread( new Runnable()
		{
			public void run()
			{
				SupermanagerServiceHelper.getInstance(CreatePrivateLeagueActivity.this).
					createPrivateLeague(handler, name, maxEquips, maxEquipsPlayer, pass1, pass2, emailsToSend);
			}
		}).start();
	}
	
	CreatePrivateLeagueHandler handler = new CreatePrivateLeagueHandler()
	{

		@Override
		public void createOk(Message msg) 
		{
			// mostrem create ok
	        progress.setMessage(getString(R.string.private_league_create_progress_refresh));
	        
			// enviar a parsejar lligues privades per veure canvis
	        SupermanagerServiceHelper.getInstance(CreatePrivateLeagueActivity.this).
	        	getPrivateLeagues(privateLeagueHandler);
		}

		@Override
		public void authError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_CREATE);
			
	        // mostrem error
	        Toast.makeText(CreatePrivateLeagueActivity.this, R.string.private_league_create_auth_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void otherError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_CREATE);
	        
	        // mostrem error
	        Toast.makeText(CreatePrivateLeagueActivity.this, R.string.private_league_create_other_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void connectivityError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_CREATE);	
	        
	        // mostrem error
	        Toast.makeText(CreatePrivateLeagueActivity.this, R.string.private_league_create_connectivity_error, Toast.LENGTH_LONG).show();
		}
	};
	
	PrivateLeagueHandler privateLeagueHandler = new PrivateLeagueHandler() 
	{
		@Override
		public void authError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_CREATE);
	        
	        // mostrem error
	        Toast.makeText(CreatePrivateLeagueActivity.this, R.string.private_league_create_auth_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void otherError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_CREATE);	
	        
	        // mostrem error
	        Toast.makeText(CreatePrivateLeagueActivity.this, R.string.private_league_create_other_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void connectivityError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_CREATE);
	        
	        // mostrem error
	        Toast.makeText(CreatePrivateLeagueActivity.this, R.string.private_league_create_connectivity_error, Toast.LENGTH_LONG).show();
		}
		
		@Override
		public void privateLeagueParsed() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_CREATE);
	        
	        // mostrem error
	        Toast.makeText(CreatePrivateLeagueActivity.this, R.string.private_league_create_refresh, Toast.LENGTH_LONG).show();

	        // sortir de l'activity
	        CreatePrivateLeagueActivity.this.finish();
		}
	};
}
